using System;
using System.Threading;

namespace Lucene.Linq.VSTests.Helpers
{
    public sealed class ThreadRunner {
        private Exception _catchedException;
        private Delegate _start;
        private Object[] _args;
        public ThreadRunner(Delegate start, params object[] args) {
            _start = start;
            _args = args;
        }

        public Exception CatchedException {
            get { return _catchedException; }
        }

        private void GuardedStart() {
            try {
                _start.DynamicInvoke(this._args);
            } catch (Exception ex) {
                _catchedException = ex;
            }
        }

        public void Run() {
            Thread thread = new Thread(GuardedStart);
            thread.Start();
            while (thread.ThreadState == ThreadState.Running) {
                Thread.Sleep(0);
            }
        }
    }
}